package cn.tedu.hotel.service.impl;

import cn.tedu.hotel.ex.ServiceException;
import cn.tedu.hotel.mapper.FacilitiesMapper;
import cn.tedu.hotel.mapper.RoomMapper;
import cn.tedu.hotel.pojo.dto.FacilitiesAddNewDTO;
import cn.tedu.hotel.pojo.entity.Facilities;
import cn.tedu.hotel.pojo.vo.FacilitiesListItemVO;
import cn.tedu.hotel.pojo.vo.FacilitiesStandardVO;
import cn.tedu.hotel.pojo.vo.RoomStandardVO;
import cn.tedu.hotel.service.IFacilitiesService;
import cn.tedu.hotel.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 *  处理房间设施业务的实现类
 */
@Slf4j
@Service
public class FacilitiesServiceImpl implements IFacilitiesService, ServiceCode {

    @Autowired
    private FacilitiesMapper facilitiesMapper;
    @Autowired
    private RoomMapper roomMapper;

    public FacilitiesServiceImpl(){
        log.debug("创建业务对象：FacilitiesServiceImpl");
    }

    @Override
    public void addNew(FacilitiesAddNewDTO facilitiesAddNewDTO) {
        log.debug("开始处理【添加房间设施】的业务，参数：{}",facilitiesAddNewDTO);
        Long roomId = facilitiesAddNewDTO.getRoomId();

        //检查房间是否存在
        RoomStandardVO queryResult = roomMapper.getStandardById(roomId);
        if (queryResult == null){
            String message = "添加失败，房间不存在";
            log.warn(message);
            throw new ServiceException(ERR_NOT_FOUND,message);
        }

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //创建对象
        Facilities facilities = new Facilities();
        //补全属性数据
        BeanUtils.copyProperties(facilitiesAddNewDTO,facilities);
        facilities.setGmtCreate(now);
        facilities.setGmtModified(now);

        //执行插入
        int rows = facilitiesMapper.insert(facilities);
        if (rows != 1){
            String message = "添加失败，服务器繁忙，请稍后再试";
            log.warn(message);
            throw new ServiceException(ERR_INSERT,message);
        }
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始处理【根据id删除房间设施】，房价设施id：{}",id);
        //检查房价设施是否存在
        FacilitiesStandardVO queryResult = facilitiesMapper.getStandardById(id);
        if (queryResult == null){
            String message = "删除失败，房间不存在";
            log.warn(message);
            throw new ServiceException(ERR_NOT_FOUND,message);
        }

        //执行删除
        int rows = facilitiesMapper.deleteById(id);
        if (rows != 1){
            String message = "删除失败，服务器繁忙，请稍后再试";
            log.warn(message);
            throw new ServiceException(ERR_INSERT,message);
        }
    }

    @Override
    public List<FacilitiesListItemVO> listFacilities() {
        log.debug("开始处理【查询房间设施】的业务");
        return facilitiesMapper.listFacilities();
    }
}
